//============================================================================
// Name        : t3.cpp
// Author      : 
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <assert.h>
#include <pthread.h>
#include <unistd.h>

using namespace std;

#include "MyQueue.h"


#define QUEUE_SIZE 10
#define TEST_SIZE 100

const int INVALID_QUEUE = -1;


void *consumeData( void* p )
{

  if( p == NULL )
  {
    pthread_exit( (void*)&INVALID_QUEUE );
  }
  MyQueue<int, QUEUE_SIZE> *pQueue = (MyQueue<int, QUEUE_SIZE> *)p;

  for (int i = 0; i < TEST_SIZE; ++i)
  {
    int value;
    pQueue->get( value );
    cout << value << " ";
    sleep(1);
  }
  pthread_exit(NULL);
}

void *produceData( void* p )
{
  sleep(2);
  if( p == NULL )
  {
    pthread_exit( (void*)&INVALID_QUEUE );
  }
  MyQueue<int, QUEUE_SIZE> *pQueue = (MyQueue<int, QUEUE_SIZE> *)p;

  for (int i = 0; i < TEST_SIZE; ++i)
  {
    pQueue->add( i );
    sleep(1);
  }
  pthread_exit(NULL);
}

int
main ()
{
  cout << "starting..." << endl;

  MyQueue<int, 10> queue;

  pthread_t thread1, thread2;

  int ret1 = pthread_create( &thread1, NULL, produceData, (void*)&queue );
  if (ret1)
  {
    cout << "Error Create 1st thread - pthread_create() return code: " << ret1 << endl;
    return 1;
  }

  int ret2 = pthread_create( &thread2, NULL, consumeData, (void*)&queue );
  if (ret1)
  {
    cout << "Error Create 2nd thread - pthread_create() return code: " << ret2 << endl;
    return 1;
  }

  //wait;
  pthread_join( thread1, NULL);
  pthread_join( thread2, NULL);

  cout << endl;
  cout << "ended." << endl;
}

